package com.sg.business.visualization.view.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;

import com.sg.business.visualization.model.ProjectSelectProvider;
import com.sg.business.visualization.ui.AbstractProjectVisualization;
import com.sg.business.visualization.ui.DurationOfProjectSetting;

public class QueryProject extends AbstractHandler {

	@Override
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		Shell parent = HandlerUtil.getActiveShell(event);
		IWorkbenchPart part = HandlerUtil.getActivePart(event);
		if (part instanceof AbstractProjectVisualization) {
			final AbstractProjectVisualization view = (AbstractProjectVisualization) part;
			ProjectSelectProvider projectProvider = view.getProjectSelectProvider();
			DurationOfProjectSetting shell = new DurationOfProjectSetting(
					parent, projectProvider) {
				@Override
				protected void setFilter(int yearIndex, int quarterIndex,
						int monthIndex, boolean clearFilter) {
					super.setFilter(yearIndex, quarterIndex, monthIndex,
							clearFilter);
					view.doRefresh();
				}
			};
			Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
			ToolBar control = ((ToolItem) ((Event) event.getTrigger()).widget).getParent();
			Point location = control.toDisplay(0, control.getBounds().height);
			Rectangle displayBounds = Display.getCurrent().getBounds();
			if(location.x+size.x+4>displayBounds.width){
				location.x = displayBounds.width - size.x - 4;
			}
			
			shell.open(location);
		}

		return null;
	}
}
